package fr.liglab.adele.icasa.impl;

import java.text.DecimalFormat;
import java.text.NumberFormat;

import org.apache.felix.ipojo.annotations.Component;
import org.apache.felix.ipojo.annotations.Invalidate;
import org.apache.felix.ipojo.annotations.Provides;
import org.apache.felix.ipojo.annotations.Requires;
import org.apache.felix.ipojo.annotations.ServiceProperty;
import org.apache.felix.ipojo.annotations.Validate;

import fr.liglab.adele.icasa.EcoHeating;
import fr.liglab.adele.icasa.device.DeviceListener;
import fr.liglab.adele.icasa.device.temperature.Heater;
import fr.liglab.adele.icasa.device.temperature.Thermometer;
import fr.liglab.adele.icasa.environment.SimulatedEnvironment;
import fr.liglab.adele.icasa.environment.SimulatedEnvironmentManager;

@Component
@Provides
public class EcoHeatingImpl implements EcoHeating, DeviceListener{

	@Requires
	Heater heater;

	@Requires
	Thermometer thermometer;

	@Requires
	SimulatedEnvironmentManager manager;
	
	@Requires
	SimulatedEnvironment environment;
	
	@ServiceProperty(value = "1", mandatory = false)
	float temperature;

	@Validate
	public void starting() {
		
		manager.bindDeviceToEnvironment("nameHeater", "enclosedEnvironment");
		manager.bindDeviceToEnvironment("nameThermometer", "enclosedEnvironment");
		
		environment.setProperty(SimulatedEnvironment.VOLUME, 2.0d);
		environment.setProperty(SimulatedEnvironment.TEMPERATURE, 0.1d);

		System.out.println("<init-environment volume="
				+ environment.getProperty(SimulatedEnvironment.VOLUME)
				+ " temperature="
				+ environment.getProperty(SimulatedEnvironment.TEMPERATURE)				
				+ " heater_power="
				+ heater.getPowerLevel()
				+ " />");

		thermometer.addListener(this);		

	}

	@Invalidate
	public void stopping() {
		//DO ME
	}

	public void notifyDeviceEvent() {
		//System.out.format("%.3f%n", 2.0);
		NumberFormat formatter = new DecimalFormat("#0.00");
		double currentTemperature = thermometer.getTemperature();
		System.out.println("<eco-heating current=" + formatter.format(currentTemperature)
				+ " target=" + formatter.format(temperature) + " heater_power="+formatter.format(heater.getPowerLevel())+" />");
		if (currentTemperature < temperature && heater.getPowerLevel()<1.0) {
			heater.setPowerLevel(heater.getPowerLevel() + 0.1);
		} else if (currentTemperature > temperature && heater.getPowerLevel()>0.1) {
			//heater.setPowerLevel(0.0);
			heater.setPowerLevel(heater.getPowerLevel() - 0.1);
		}else {
			System.out.println("<eco-heating>heater stay in the same temperature</eco-heating>");
		}
		
	}

}
